import { ReloadOutlined } from '@ant-design/icons'
import { type MaySuccess, success } from '@gnlab/utils'
import { message, Button, Input } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import { makeTextWord } from '@/services/common/definition'
import { type HistoryItem } from '@/services/features/robot'

export function SaveMatchReplyModal({
  profileId,
  records,
  onFinish,
}: {
  profileId: number
  records: HistoryItem[] | null
  onFinish: () => void
}) {
  return <EditModal title="保存机器人语料" open={!!records} onCancel={onFinish} width={750}>
    {records ? <Content profileId={profileId} records={records} onFinish={onFinish} /> : null}
  </EditModal>
}

function Content({
  profileId,
  records,
  onFinish,
}: {
  profileId: number
  records: HistoryItem[]
  onFinish: () => void
}) {
  const [summary, setSummary] = useState<MaySuccess<
    string,
    { message: string; code?: string }
  > | null>(null)
  const [summaryValue, setSummaryValue] = useState('') // 用于文本框编辑
  const generateSummary = useCallback(() => {
    setSummary(null)
    void services.features.robot.summary(profileId, records).then(res => {
      if (res.success) {
        setSummary(success(res.data.summary))
        setSummaryValue(res.data.summary)
      } else {
        setSummary(res)
      }
    })
  }, [profileId, records])
  useEffect(() => generateSummary(), [generateSummary])

  const [match, setMatch] = useState(() => {
    return (
      [...records]
        .reverse()
        .filter(v => v.isReceive)
        .slice(0, 1)
        .map(v => v.text)[0] ?? ''
    )
  })
  const [reply, setReply] = useState(() => {
    return (
      [...records]
        .reverse()
        .filter(v => !v.isReceive)
        .slice(0, 1)
        .map(v => v.text)[0] ?? ''
    )
  })

  const [saving, setSaving] = useState(false)
  async function save() {
    setSaving(true)
    const res = await services.features.robot.addMatchReplyRule({
      profileId,
      summary: summaryValue,
      match,
      reply: makeTextWord(reply),
    })
    setSaving(false)
    if (res.success) {
      void message.success('语料保存成功')
      onFinish()
    } else {
      void message.warning(res.error.message)
    }
  }

  return <>
    <main css={styles.main}>
      {summary && !summary.success ? (
        <div css={[styles.item, styles.failed]}>场景生成失败：{summary.error.message}</div>
      ) : null}
      <div css={styles.item}>
        <label>场景：</label>
        <Input.TextArea
          disabled={!summary}
          value={summary ? summaryValue : '生成中...'}
          onChange={e => setSummaryValue(e.target.value)}
        />
        {summary ? (
          <Button type="link" icon={<ReloadOutlined />} onClick={generateSummary}>
            重新生成
          </Button>
        ) : null}
      </div>
      <div css={styles.item}>
        <label>匹配语句：</label>
        <Input.TextArea value={match} onChange={e => setMatch(e.target.value)} />
      </div>
      <div css={styles.item}>
        <label>答复：</label>
        <Input.TextArea value={reply} onChange={e => setReply(e.target.value)} />
      </div>
    </main>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" onClick={save} disabled={!summary || saving}>
        确定
      </Button>
    </footer>
  </>
}

const styles = {
  main: css`
    margin-top: 20px;
  `,
  item: css`
    display: flex;
    align-items: baseline;
    margin-bottom: 1.5em;
    label {
      width: 6em;
      text-align: right;
      margin-right: 1em;
    }
    label + * {
      width: 30em;
    }
  `,
  failed: css`
    color: red;
    word-break: break-all;
    word-wrap: break-word;
  `,
}
